<template>
  <div>
    <el-dialog
      title="导出配置"
      :visible.sync="showExport"
      width="40%"
      height="600px"
    >
      <el-form ref="form" label-width="100px">
        <el-form-item label="vue文件名">
          <el-input
            v-model="fileName"
            placeholder="请输入vue文件名，不带.vue"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showExport = false">取 消</el-button>
        <el-button :loading="downlodaLoading" type="primary" @click="exportFile"
          >导出</el-button
        >
      </div>
    </el-dialog>
    <input id="copyNode" type="hidden" />
  </div>
</template>

<script>
import { saveAs } from "file-saver";
import JSZip from "jszip";
import common from "../common";
export default {
  name: "ExportDialog",
  mixins: [common],
  components: {},
  props: {},
  data() {
    return {
      formData: {},
      downlodaLoading: false,
      fileName: "",
      showExport: false,
    };
  },
  methods: {
    showDialog() {
      this.showExport = true;
    },
    // 导出文件
    exportFile() {
      const zip = new JSZip();
      const cache = {};
      if (!this.fileName) {
        this.$message({
          type: "info",
          message: "请输入文件名",
        });
        return;
      }
      this.downlodaLoading = true;
      const codeStr = this.generateCode();
      const echartsCode = this.generateEchartsCode();
      const file_name = `${this.fileName}.vue`;
      if (!echartsCode.replace(/\s+/g, "")) {
        const blob = new Blob([codeStr], { type: "text/plain;charset=utf-8" });
        saveAs(blob, `${this.fileName}.vue`);
        this.downlodaLoading = false;
      } else {
        zip.file(file_name, codeStr, { binary: true }); // vue文件
        cache[file_name] = codeStr;
        zip.file(`echartsOptions.js`, echartsCode, { binary: true }); // echarts配置
        zip.generateAsync({ type: "blob" }).then((content) => {
          // 生成二进制流
          saveAs(content, `${this.fileName}.zip`); // 利用file-saver保存文件  自定义文件名
          this.downlodaLoading = false;
        });
      }
    },
  },
};
</script>

<style scoped>
</style>